package org.jeecg.modules.bid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.bid.entity.Bid;
import org.jeecg.modules.bid.entity.BidManagement;
import org.jeecg.modules.bid.mapper.BidManagementMapper;
import org.jeecg.modules.bid.service.IBidManagementService;
import org.jeecg.modules.bid.service.IBidService;
import org.jeecg.modules.bid.vo.BidManagementVO;
import org.jeecg.modules.bid.vo.BidVo;
import org.jeecg.modules.purchase.entity.PurchasePlan;
import org.jeecg.modules.purchase.service.IPurchasePlanService;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 投标管理表服务实现类
 * @Author: jeecg-boot
 * @Date: 2025-10-16
 * @Version: V1.0
 */
@Service
@Slf4j
public class BidManagementServiceImpl extends ServiceImpl<BidManagementMapper, BidManagement> implements IBidManagementService {

    /**
     * 将投标状态数字转换为文字描述
     * @param status 状态数字
     * @return 状态文字描述
     */
    private String getBidStatusText(String status) {
        if (status == null) {
            return "";
        }
        switch (status) {
            case "0":
                return "投标中";
            case "1":
                return "评标中";
            case "2":
                return "已完成";
            case "3":
                return "已取消";
            default:
                return status;
        }
    }

    @Autowired
    private IBidService bidService;

    @Autowired
    private IPurchasePlanService purchasePlanService;

    @Autowired
    private ISupplierService supplierService;

    @Override
    public BidManagementVO getBidManagementDetailById(String id) {
        // 根据ID获取投标管理对象
        BidManagement bidManagement = this.getById(id);
        if (bidManagement == null) {
            return null;
        }

        // 创建视图对象并复制属性
        BidManagementVO bidManagementVo = new BidManagementVO();
        BeanUtils.copyProperties(bidManagement, bidManagementVo);

        // 查询投标供应商列表
        QueryWrapper<Bid> bidQueryWrapper = new QueryWrapper<>();
        bidQueryWrapper.eq("purchase_id", bidManagement.getPurchaseId());
        bidQueryWrapper.in("bid_status", Arrays.asList(1,2,4));
        List<Bid> bidList = bidService.list(bidQueryWrapper);
        bidManagementVo.setBid(bidList);

        // 查询未投标供应商列表
        QueryWrapper<Bid> notBidQueryWrapper = new QueryWrapper<>();
        notBidQueryWrapper.eq("purchase_id", bidManagement.getPurchaseId());
        notBidQueryWrapper.in("bid_status", Arrays.asList(0, 3));
        List<Bid> notBidList = bidService.list(notBidQueryWrapper);
        bidManagementVo.setNotbid(notBidList);


    // 1.查询已投标的供应商，但是返回的是BidVo
     // 查询投标供应商列表
        QueryWrapper<Bid> bidVoQueryWrapper = new QueryWrapper<>();
        bidVoQueryWrapper.eq("purchase_id", bidManagement.getPurchaseId());
        bidVoQueryWrapper.in("bid_status", Arrays.asList(1,2,4));
    //2.设置排序规则:isWinning==1的排在前面
        bidVoQueryWrapper.orderByDesc("is_winning");
        List<Bid> bidList2 = bidService.list(bidVoQueryWrapper);

        // 3.创建BidVo列表并遍历结果
        List<BidVo> bidVoList = new ArrayList<>();
        for (Bid bid : bidList2) {
            BidVo bidVo = new BidVo();
            bidVo.setBid(bid);

            // 3.用bid的supplierId查找supplier的totalScore
            if (bid.getSupplierId() != null) {
                Supplier supplier = supplierService.getById(bid.getSupplierId());
                if (supplier != null && supplier.getTotalScore() != null) {
                    // 4.把totalScore传入对应的BidVo
                    bidVo.setTotalScore(supplier.getTotalScore());
                }
            }
            bidVoList.add(bidVo);
        }

        // 设置到bidManagementVo中bidVos
        bidManagementVo.setBidVos(bidVoList);

        return bidManagementVo;
    }


    public Boolean createBidManagementFromPurchase(String purchaseId) {
        // 创建投标管理对象
        BidManagement bidManagement = new BidManagement();

        try {
            // 根据采购方案ID获取采购方案信息
            PurchasePlan purchasePlan = purchasePlanService.getById(purchaseId);

            if (purchasePlan == null) {
//                logger.error("采购方案信息为空，采购方案ID：{}", purchaseId);
                return false;
            }

            // 设置投标管理对象的属性
            bidManagement.setProjectName(purchasePlan.getProjectName());
            bidManagement.setSchemeType(purchasePlan.getSchemeType());
            bidManagement.setOpeningTime(purchasePlan.getOpeningTime());
            bidManagement.setBidStatus("0");
            bidManagement.setBudgetAmount(purchasePlan.getBudgetAmount());
            bidManagement.setBudgetAmount(purchasePlan.getBudgetAmount());
            bidManagement.setProjectNumber(purchasePlan.getProjectNumber());
            bidManagement.setCategory(purchasePlan.getCategory());
            bidManagement.setRegistrationDeadline(purchasePlan.getBiddingEndTime());
            bidManagement.setAnnouncementTime(purchasePlan.getAnnouncementEndTime());
            bidManagement.setPurchaseId(purchaseId);
            bidManagement.setCreateTime(new Date());

            // 保存投标管理对象
            if (this.save(bidManagement)) {

                return true;
            } else {

                return false;
            }
        } catch (Exception e) {

            return false;
        }
    }

    @Override
    public boolean markAsCompleted(String id, String username) {
        // 根据ID获取投标管理对象
        BidManagement existingBid = this.getById(id);
        if (existingBid == null) {
            return false;
        }

        // 更新投标状态为已完成
        existingBid.setBidStatus("2");

        // 根据purchaseId、supplierId、lotteryId查找proc_bid表对应的信息
        QueryWrapper<Bid> bidQueryWrapper = new QueryWrapper<>();
        bidQueryWrapper.eq("purchase_id", existingBid.getPurchaseId())
                .eq("supplier_id", existingBid.getSupplierId())
                .eq("lottery_id", existingBid.getLotteryId());
        Bid bid = bidService.getOne(bidQueryWrapper);

        // 如果找到对应的bid记录，也更新其状态
        if (bid != null) {
            bid.setBidStatus("4");
            bid.setUpdateBy(username);
            bid.setUpdateTime(new Date());
            bidService.updateById(bid);
        }

        // 更新投标管理记录
        return this.updateById(existingBid);

    }

    @Override
    public BidManagementVO getBidManagementByPurchaseId(String purchaseId){
        BidManagement bidManagement = baseMapper.getBidManagementByPurchaseId(purchaseId);
        BidManagementVO  bidManagementVO = new BidManagementVO();
        BeanUtils.copyProperties(bidManagement,bidManagementVO);
        return bidManagementVO;
    }

    @Override
    public void exportExcelByIds(List<String> ids, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 查询数据
        QueryWrapper<BidManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", ids);
        List<BidManagement> list = this.list(queryWrapper);

        // 检查数据列表是否为空
        if (list == null || list.isEmpty()) {
            log.warn("Excel导出数据为空，ids: {}", ids);
            // 当没有数据时，创建一个包含标题的空Excel文件
            // 使用ByteArrayOutputStream缓存Excel数据
            try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
                // 创建一个空的工作簿
                XSSFWorkbook workbook = new XSSFWorkbook();
                // 创建一个工作表
                XSSFSheet sheet = workbook.createSheet("投标管理列表");

                // 创建表头行，与实际数据字段匹配
                XSSFRow headerRow = sheet.createRow(0);
                String[] headers = {"项目名称", "方案类型", "开标时间", "投标状态", "中标金额(万元)", "中标人", "发布状态", "项目类别", "报名截止时间", "公告时间"};
                for (int i = 0; i < headers.length; i++) {
                    XSSFCell cell = headerRow.createCell(i);
                    cell.setCellValue(headers[i]);
                }

                // 创建日期格式
                XSSFCellStyle dateCellStyle = workbook.createCellStyle();
                XSSFDataFormat dataFormat = workbook.createDataFormat();
                dateCellStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); // 设置日期格式为年-月-日

                // 写入空工作簿到字节数组输出流
                workbook.write(byteArrayOutputStream);
                workbook.close();
                byteArrayOutputStream.flush();

                // 获取Excel数据的字节数组
                byte[] excelData = byteArrayOutputStream.toByteArray();

                // 重置响应
                response.reset();

                // 设置响应头，确保浏览器正确识别下载文件
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setDateHeader("Expires", 0);

                // 设置Content-Length头，确保浏览器知道文件大小
                response.setContentLength(excelData.length);

                // 设置文件名，确保多浏览器兼容性
                String fileName = "投标管理数据.xlsx";
                String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

                // 写入响应
                try (OutputStream out = response.getOutputStream()) {
                    out.write(excelData);
                    out.flush();
                    response.flushBuffer(); // 确保所有数据都被写入响应
                }

                // 记录导出成功日志
                log.info("空Excel导出成功，写入字节数: {}", excelData.length);
                return;
            } catch (Exception e) {
                log.error("空Excel导出失败", e);
                throw e;
            }
        }

        // 使用手动创建Excel的方式，避免自动合并单元格导致的错误
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            // 创建工作簿
            XSSFWorkbook workbook = new XSSFWorkbook();
            // 创建工作表
            XSSFSheet sheet = workbook.createSheet("投标管理列表");

            // 创建表头行
            XSSFRow headerRow = sheet.createRow(0);
            // 定义表头列名，根据用户要求包含指定字段
            String[] headers = {"项目名称", "方案类型", "开标时间", "投标状态", "中标金额(万元)", "中标人", "发布状态", "项目类别", "报名截止时间", "公告时间"};
            for (int i = 0; i < headers.length; i++) {
                XSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 创建日期格式
            XSSFCellStyle dateCellStyle = workbook.createCellStyle();
            XSSFDataFormat dataFormat = workbook.createDataFormat();
            dateCellStyle.setDataFormat(dataFormat.getFormat("yyyy-MM-dd")); // 设置日期格式为年-月-日

            // 填充数据行
            for (int i = 0; i < list.size(); i++) {
                BidManagement bid = list.get(i);
                XSSFRow dataRow = sheet.createRow(i + 1);

                // 根据用户要求的字段设置单元格值
                // 基本信息
                dataRow.createCell(0).setCellValue(bid.getProjectName() != null ? bid.getProjectName() : "");
                dataRow.createCell(1).setCellValue(bid.getSchemeType() != null ? bid.getSchemeType() : "");

                // 用户要求的字段
                // 开标时间 - 设置日期格式
                XSSFCell openingTimeCell = dataRow.createCell(2);
                if (bid.getOpeningTime() != null) {
                    openingTimeCell.setCellValue(bid.getOpeningTime());
                    openingTimeCell.setCellStyle(dateCellStyle); // 应用日期格式
                } else {
                    openingTimeCell.setCellValue("");
                }

                // 投标状态 - 将数字状态转换为文字描述
                String bidStatusText = getBidStatusText(bid.getBidStatus());
                dataRow.createCell(3).setCellValue(bidStatusText);
                // 中标金额
                dataRow.createCell(4).setCellValue(bid.getBidPrice() != null ? bid.getBidPrice().toString() : "");
                // 中标人
                dataRow.createCell(5).setCellValue(bid.getWinningName() != null ? bid.getWinningName() : "");
                // 发布状态
                dataRow.createCell(6).setCellValue(bid.getPublishedStatus() != null ? bid.getPublishedStatus() : "");
                // 项目类别
                dataRow.createCell(7).setCellValue(bid.getCategory() != null ? bid.getCategory() : "");

                // 报名截止时间 - 设置日期格式
                XSSFCell registrationDeadlineCell = dataRow.createCell(8);
                if (bid.getRegistrationDeadline() != null) {
                    registrationDeadlineCell.setCellValue(bid.getRegistrationDeadline());
                    registrationDeadlineCell.setCellStyle(dateCellStyle); // 应用日期格式
                } else {
                    registrationDeadlineCell.setCellValue("");
                }

                // 公告时间 - 设置日期格式
                XSSFCell announcementTimeCell = dataRow.createCell(9);
                if (bid.getAnnouncementTime() != null) {
                    announcementTimeCell.setCellValue(bid.getAnnouncementTime());
                    announcementTimeCell.setCellStyle(dateCellStyle); // 应用日期格式
                } else {
                    announcementTimeCell.setCellValue("");
                }
            }

            // 将Excel写入ByteArrayOutputStream
            workbook.write(byteArrayOutputStream);
            workbook.close(); // 关闭工作簿
            byteArrayOutputStream.flush();

            // 获取Excel数据的字节数组
            byte[] excelData = byteArrayOutputStream.toByteArray();

            // 重置响应
            response.reset();

            // 设置响应头，确保浏览器正确识别下载文件
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setDateHeader("Expires", 0);

            // 设置Content-Length头，确保浏览器知道文件大小
            response.setContentLength(excelData.length);

            // 设置文件名，确保多浏览器兼容性
            String fileName = "投标管理数据.xlsx";
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);

            // 写入响应
            try (OutputStream out = response.getOutputStream()) {
                out.write(excelData);
                out.flush();
                response.flushBuffer(); // 确保所有数据都被写入响应
            }

            // 记录导出成功日志
            log.info("Excel导出成功，写入字节数: {}", excelData.length);
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            throw e;
        }
    }
}
